﻿#ifndef XRTCCLIENT_CODECS_H264_ENCODER_IMPL_H_
#define XRTCCLIENT_CODECS_H264_ENCODER_IMPL_H_

#include <modules/video_coding/codecs/h264/include/h264.h>
#include <common_video/h264/h264_bitstream_parser.h>
#include <wels/codec_api.h>

namespace xrtc {

class H264EncoderImpl : public webrtc::VideoEncoder {
public:
    struct LayerConfig {
        int width = -1; // 图像的宽度
        int height = -1; // 图像的高度
        bool sending = true; // 编码器是否是工作状态
        bool key_frame_request = false; // 编码器是否被请求过关键帧
        float max_frame_rate = 0; // 最大帧率
        uint32_t target_bps = 0; // 目标码率
        uint32_t max_bps = 0; // 最大码率
        bool frame_dropping_on = false; // 是否开启丢帧策略
        int key_frame_interval = 0; // 关键帧的间隔
        int num_temporal_layers = 1; // 时域层的个数

        void SetStreamState(bool send_stream);
    };

    H264EncoderImpl(const cricket::VideoCodec& codec);
    ~H264EncoderImpl() override;

    int InitEncode(const webrtc::VideoCodec* inst,
        const VideoEncoder::Settings& settings) override;

    int32_t RegisterEncodeCompleteCallback(
        webrtc::EncodedImageCallback* callback) override;

    int32_t Release() override;

    int32_t Encode(const webrtc::VideoFrame& frame,
        const std::vector<webrtc::VideoFrameType>* frame_types) override;

    void SetRates(const RateControlParameters& parameters) override;
    EncoderInfo GetEncoderInfo() const override;

private:
    SEncParamExt CreateEncoderParams();

private:
    ISVCEncoder* openh264_encoder_ = nullptr;
    SSourcePicture picture_ = { 0 };
    webrtc::VideoCodec codec_;
    webrtc::H264PacketizationMode packetization_mode_;
    size_t max_payload_size_ = 0;
    webrtc::EncodedImage encoded_image_;
    LayerConfig config_;
    webrtc::EncodedImageCallback* encoded_image_callback_ = nullptr;
    webrtc::H264BitstreamParser h264_bitstream_parser_;
};

} // namespace xrtc


#endif // XRTCCLIENT_CODECS_H264_ENCODER_IMPL_H_